//
//  KATimer.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//

import Foundation

class KATimer {
    private static var timers = [String: DispatchSourceTimer]()
    private static let semaphore = DispatchSemaphore(value: 1)
    
    static func execTask(_ task: @escaping () -> Void, start: TimeInterval, interval: TimeInterval, repeats: Bool, async: Bool) -> String? {
        guard interval > 0 || !repeats else { return nil }
        
        let queue = async ? DispatchQueue.global() : DispatchQueue.main
        let timer = DispatchSource.makeTimerSource(queue: queue)
        timer.schedule(deadline: .now() + start, repeating: interval)
        
        semaphore.wait()
        let name = "\(timers.count)"
        timers[name] = timer
        semaphore.signal()
        
        timer.setEventHandler {
            task()
            if !repeats {
                cancelTask(name)
            }
        }
        
        timer.resume()
        return name
    }
    
    static func execTask(_ target: AnyObject, selector: Selector, start: TimeInterval, interval: TimeInterval, repeats: Bool, async: Bool) -> String? {
        guard target.responds(to: selector) else { return nil }
        return execTask({
            target.perform(selector)
        }, start: start, interval: interval, repeats: repeats, async: async)
    }
    
    static func cancelTask(_ name: String) {
        guard !name.isEmpty else { return }
        
        semaphore.wait()
        if let timer = timers[name] {
            timer.cancel()
            timers.removeValue(forKey: name)
        }
        semaphore.signal()
    }
}



